<?php
//初始化设置
define("CT",1);
date_default_timezone_set('PRC');  //设置默认时区
define('ROOT_PATH',  str_replace('\\', '/', dirname(dirname(dirname(__FILE__))))."/");
define('PAGE_SIZE',  20);

//引入配置文件
$domain = $_SERVER["HTTP_HOST"];
@ini_set("session.cookie_domain", $domain);

require_once(ROOT_PATH."lib/db_init.php");//引入数据库文件
require_once(ROOT_PATH."lib/jssdk.php");
require_once(ROOT_PATH."application/constant/Constant.php");
require_once(ROOT_PATH."lib/cls_smarty.php");//引入模板文件

$smarty=new Smarty();

$smarty->template_dir   = ROOT_PATH . 'application/views/wap/';
$smarty->compile_dir    = ROOT_PATH . 'temp/compiled';

/*载入公共库文件*/
require_once(ROOT_PATH."lib/lib_base.php");
require_once(ROOT_PATH."lib/PageUtil.php");

//基本设置结束--------------

//读取系统设定
$setting = $db->getRow("select * from " . table("setting"));
$smarty->assign("setting", $setting);

define('CP_USER', $setting["cp_user"]);
define('API_KEY', $setting["api_key"]);
define('SECRET_KEY', $setting["secret_key"]);

$appId = $setting["appid"];
$appSecret = $setting["appsecret"];
$openid = $_COOKIE["mb_web_traffic_openid"];

if($_GET["openid"] == "oHbw8t0aZ__kCoLONSdXuQoF9-a8") {
	$openid = "oHbw8t0aZ__kCoLONSdXuQoF9-a8";
	setcookie("mb_web_traffic_openid", $openid, time() + 604800, '/', "");
}

//读取openid
if(!$openid) {
	if(!$_GET["code"]) {
		$url =  'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		header("location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appId&redirect_uri=" . urlencode($url) . "&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
		exit();
	} else {
		$url =  'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
		$code = trim($_GET["code"]);
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
		$json_ret = json_decode(file_get_contents($url),true);
		$openid = $json_ret["openid"];
		setcookie("mb_web_traffic_openid", $openid, time() + 604800, '/', "");
	}
// } else {
// 	setcookie("mb_web_traffic_openid", $openid, time() + 604800, '/', "");
	
}

//读取用户信息
$jssdk = new JSSDK($appId, $appSecret);
$accessToken = $jssdk->getAccessToken();
$signPackage = $jssdk->GetSignPackage();
$subscribe = 0;

$userUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
$userData = json_decode(file_get_contents($userUrl),true);

if(!isset($userData["errcode"])) {
	$cnt = $db->getOne("select count(1) from " . table("user") . " where openid = '$openid'");
	$subscribe 				= $userData["subscribe"];
	$user["follow_flag"] 	= $subscribe;
	
	if($subscribe == 1) {
		$user["nickname"] 		= addslashes($userData["nickname"]);
		$user["name"] 			= addslashes($userData["nickname"]);
		$user["head_img"] 		= $userData["headimgurl"];
		$user["gender"] 		= $userData["sex"];
		$user["wx_country"] 	= $userData["country"];
		$user["wx_prov"] 		= $userData["province"];
		$user["wx_city"] 		= $userData["city"];
		$user["openid"] 		= $userData["openid"];
		$user["follow_time"] 	= date("Y-m-d H:i:s", $userData["subscribe_time"]);
		$user["update_time"] 	= getNowTime();
	
		if($cnt) {
			$db->update("user", $user, " and openid = '$openid'");
		} else {
			$user["insert_time"] = getNowTime();
			$db->insert("user", $user);
		}
	} else if($cnt){
		$db->update("user", $user, " and openid = '$openid'");
	}
}

//页面参数判断
$m = isset($_GET['m']) ? htmlspecialchars($_GET['m']) : "index";
$m = str_replace(array("/","\\"),"",$m);

if(!file_exists(ROOT_PATH . "application/action/wap/$m.php")) {
	$m="index";
}

require_once(ROOT_PATH . "application/action/wap/$m.php");

//---------------------------通用函数---------------------------//
//页面调用通用函数
function check_login() {
	if(!$_SESSION['web_admin'] || $_SESSION['web_admin']['domain'] != $_SERVER['HTTP_HOST']) {
		header("Location:admin.php?m=logout");
		exit();
	}
	return true;
}

function haspermission($m,$a)
{
	return true;
}

function getAction()
{
	return $a = get_post("a") ? get_post("a") :  "index";
}


function getPageData($db, $sql, $page, $pageSize) {
	$rscount = $db->getOne("select count(*) from ( $sql ) temp");
	$result["rscount"] = $rscount;

	$start = ($page - 1) * $pageSize;
	$sql  .= " limit $start, $pageSize ";

	$list = $db->getAll($sql);
	$result["list"] = $list;

	$result["totalPages"] = ceil($rscount * 1.0 / $pageSize);
	$result["hasNext"] = $rscount > ($start + count($list));
	$result["hasPre"] = $page > 1;
	$result["nextPage"] = $page + 1;
	$result["prePage"] = $page - 1;
	$result["page"] = $page;
	
	return $result;
}

?>